package com.atguigu.web;


import com.atguigu.pojo.*;
import com.atguigu.service.*;
import com.atguigu.service.impl.*;
import com.atguigu.utils.WebUtils;
import com.google.gson.Gson;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.*;


public class ContainerServlet extends BaseServlet {
    ServerService serverService=new ServerServiceImpl();
    ServiceService serviceService=new ServiceServiceImpl();
    NginxServiceConfigProxyService nginxServiceConfigProxyService=new NginxServiceConfigProxyServiceImpl();
    NginxServiceConfigPhpService nginxServiceConfigPhpService=new NginxServiceConfigPhpServiceImpl();
    NginxServiceConfigTcpProxyService nginxServiceConfigTcpProxyService=new NginxServiceConfigTcpProxyServiceImpl();
    RedisServiceConfigService redisServiceConfigService=new RedisServiceConfigServiceImpl();
    MysqlServiceConfigService mysqlServiceConfigService=new MysqlServiceConfigServiceImpl();
    MongoServiceConfigService mongoServiceConfigService=new MongoServiceConfigServiceImpl();
    DockerServiceConfigService dockerServiceConfigService=new DockerServiceConfigServiceImpl();
    ContainerService containerService=new ContainerServiceImpl();

    protected void ajaxConfigContainer(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException{
        if(request.getMethod().equals("GET")){
//            String serverId=request.getParameter("serverId");
//            Server server=serverService.queryServerById(serverId);
//            if(server==null){
//                response.getWriter().write("serverId "+serverId+" not found");
//                return;
//            }
//            request.setAttribute("server",server);
//            List<Service> services=serviceService.queryServicesByServerIdAndServiceName(serverId,"docker");
//            if (services.size()!=1){
//                response.getWriter().write("本服务器: "+server.getName()+" 上服务名称异常,请查看名like docker 的服务有几个?");
//                return;
//            }
//            Service service=services.iterator().next();//拿到了 docker 服务的服务对象
//            request.setAttribute("service",service);
//            //查出这个docker服务有哪些容器
//            List<Container> containers=containerService.queryContainersByServerId(server.getId());
//            request.setAttribute("containers",containers);
//            request.getRequestDispatcher("/pages/client/container.jsp").forward(request,response);
        }else{//应对post methed
            String configType=request.getParameter("configType");
            System.out.println("这是 ServiceServlet.ajaxConfigService 的提示,configType 是: "+configType);
            String id=request.getParameter("id");
            if(request.getParameter("delete")!=null){
                if(request.getParameter("delete").equals("true")){
                    Container container=containerService.queryContainerById(id);
                    //System.out.println(id);
                    if(container==null){//容器id无效
                        response.getWriter().write("容器id无效: "+id);
                        return;
                    }else{//容器id有效就进行删除
                        //删除容器前,先放弃它使用的端口
                        String[] portMaps=container.getPortMap().split(",");
                        Service service=serviceService.queryServiceById(container.getServiceId());
                        Server server=serverService.queryServerById(container.getServerId());
                        for (String portMap:portMaps){
                            String outPort=portMap.split(":")[0];
                            service.setPorts(WebUtils.reducePortItem(service.getPorts(),outPort));
                            server.setPorts(WebUtils.reducePortItem(server.getPorts(),outPort));
                        }
                        serviceService.updateService(service);
                        serverService.updateServer(server);
                        containerService.deleteContainerById(id);
                        response.getWriter().write("删除成功");
                        return;
                    }//容器id有效就进行删除
                }
            }

            String serverId=request.getParameter("serverId");
            if(serverId==null){
                response.getWriter().write("serverId: "+serverId+" is null");
                return;
            }//处理serverId为空的情况
            Server server=serverService.queryServerById(serverId);
            if(server==null){
                response.getWriter().write("serverId: "+serverId+" not found");
                return;
            }//处理serverId传值异常的情况
            List<Service> services=serviceService.queryServicesByServerIdAndServiceName(serverId,"docker");
            if(services.size()!=1){
                response.getWriter().write("services 数量为: "+services.size()+" ,需确认名为docker的服务在 "+server.getName()+" 上有几个");
                return;
            }
            Service service=services.iterator().next();
            if(configType.equals("docker")){
                //System.out.println("delete sign:"+request.getParameter("delete"));
                String name=request.getParameter("name");
                String imageVersion=request.getParameter("imageVersion");
                String cpuMemory=request.getParameter("cpuMemory");
                if(!cpuMemory.contains("/")){//cpuMemory 传参异常处理
                    response.getWriter().write("cpuMemory传参异常: "+cpuMemory);
                }//cpuMemory 传参异常处理
                String[] strings=cpuMemory.split("/");
                String cpu=strings[0];
                String memory=strings[1];
                String volume=request.getParameter("volume");
                String ip=request.getParameter("ip");
                String use=request.getParameter("use");
                String endTime=request.getParameter("endTime");
                //既然是post上来的,先要判断是add,还是update
                //System.out.println("ContainerServlet.java:74:容器id:"+id);
                if(id==""){//containerId为空,新增container
                    Container container=new Container();
                    String portMap=request.getParameter("portMap");//现在是add阶段
                    //if(!portMap.contains(":")){//portMap 传参异常处理
                    //    response.getWriter().write("portMap传参异常: "+portMap);
                    //    return;
                    //}//传参异常 传参异常处理
                    String[] strings1=portMap.split(",");

//                    String oldPortsServer=server.getPorts();
//                    String oldPortsService=service.getPorts();
                    //老端口号弃用的逻辑
                    //add 没有老端口的问题
                    //老端口号弃用的逻辑-完
                    //新端口号使用的逻辑
//                    String needAddOutPortString="";//需要被添加的外部端口号列表
//                    for (String map:strings1) {//循环处理宿主机端口号的逻辑
//                        String[] portArray=map.split(":");
//                        String outPort= portArray[0];
//                        String insidePort= portArray[1];
//                        if (oldPortsServer.contains(outPort)){//如果包含了要更新的端口号,就别继续了
//                            response.getWriter().write("宿主机端口号: "+outPort+" 已经被使用,请在确认一下");
//                            return;
//                        }else{//如果不包含,就可以继续
//                            //既然server没用着,那么service也没用这个端口号.所以只需给service增加这个端口号即可连同server一起添加上
//                            //能用,先不用
//                            needAddOutPortString=needAddOutPortString+","+outPort;
//                        }//判断宿主机端口号是否已被使用的逻辑
//                    }//循环处理宿主机端口号的逻辑
//                    String newPortsService=WebUtils.addPortsItem(oldPortsService,needAddOutPortString);
//                    service.setPorts(newPortsService);
//                    String newPortsServer=WebUtils.addPortsItem(oldPortsServer,needAddOutPortString);
//                    server.setPorts(newPortsServer);

                    if(portMap!=""){
                        String[] allNewPortArray=portMap.split(":|,");
                        String newOutPorts="";
                        if(allNewPortArray.length%2!=0){
                            response.getWriter().write("端口对儿赋值异常:"+portMap);
                            return;
                        }
                        for(Integer i=0;i<allNewPortArray.length;i++){
                            if(i%2==0){
                                if(server.getPorts().contains(allNewPortArray[i])){
                                    response.getWriter().write(allNewPortArray[i]+"端口冲突,已在使用");
                                    return;
                                }else {
                                    Integer count=0;
                                    for(Integer n=0;n<allNewPortArray.length;n++){
                                        if(allNewPortArray[n]==allNewPortArray[i]){
                                            count++;
                                        }
                                    }
                                    if(count==1){
                                        newOutPorts=newOutPorts+","+allNewPortArray[i];
                                    }else{
                                        response.getWriter().write("外部端口重复 : "+allNewPortArray[i]);
                                        return;
                                    }
                                }
                            }
                        }
                        String newServicePorts2=WebUtils.addPortsItem(service.getPorts(),newOutPorts);
                        service.setPorts(newServicePorts2);
                        String newServerPorts2=WebUtils.addPortsItem(server.getPorts(),newOutPorts);
                        server.setPorts(newServerPorts2);
                    }
                    container.setPortMap(portMap);
                    //新端口号使用的逻辑-完

                    container.setId(WebUtils.id());
                    container.setServerId(server.getId());
                    container.setServiceId(service.getId());
                    container.setName(name);
                    container.setImageVersion(imageVersion);
                    container.setCpu(cpu);
                    container.setMemory(memory);
                    container.setVolume(volume);
                    container.setIp(ip);
//                    container.setPortMap(portMap);
                    container.setUse(use);
                    container.setEndTime(WebUtils.parseStringToDate(endTime));
                    containerService.addContainer(container);
                    response.getWriter().write("存入成功");
                }else{//containerId不为空,update
                    Container container=containerService.queryContainerById(id);
                    if(container==null){//容器id无效
                        response.getWriter().write("容器id无效: "+id);
                        return;
                    }else{//容器id有效,那就更新吧
                        String portMap=request.getParameter("portMap");
                        //开始处理 portMap
                        if(container.getPortMap().equals(portMap)){

                        }else{
                            //1.删掉老的
                            String[] allPortArray=container.getPortMap().split(":|,");
                            String outPorts="";
                            for(Integer i=0;i<allPortArray.length;i++){
                                if(i%2==0){
                                    outPorts=outPorts+","+allPortArray[i];
                                }
                            }
                            String newServicePorts=WebUtils.reducePortItem(service.getPorts(),outPorts);
                            service.setPorts(newServicePorts);
                            String newServerPorts=WebUtils.reducePortItem(server.getPorts(),outPorts);
                            server.setPorts(newServerPorts);

                            container.setPortMap("");
                            //2.加入新的
                            if(portMap!=""){
                                String[] allNewPortArray=portMap.split(":|,");
                                String newOutPorts="";
                                if(allNewPortArray.length%2!=0){
                                    response.getWriter().write("端口对儿赋值异常:"+portMap);
                                    return;
                                }
                                for(Integer i=0;i<allNewPortArray.length;i++){
                                    if(i%2==0){
                                        if(server.getPorts().contains(allNewPortArray[i])){
                                            response.getWriter().write(allNewPortArray[i]+"端口冲突,已在使用");
                                            return;
                                        }else {
                                            Integer count=0;
                                            for(Integer n=0;n<allNewPortArray.length;n++){
                                                if(allNewPortArray[n]==allNewPortArray[i]){
                                                    count++;
                                                }
                                            }
                                            if(count==1){
                                                newOutPorts=newOutPorts+","+allNewPortArray[i];
                                            }else{
                                                response.getWriter().write("外部端口重复 : "+allNewPortArray[i]);
                                                return;
                                            }
                                        }
                                    }
                                }
                                String newServicePorts2=WebUtils.addPortsItem(service.getPorts(),newOutPorts);
                                service.setPorts(newServicePorts2);
                                String newServerPorts2=WebUtils.addPortsItem(server.getPorts(),newOutPorts);
                                server.setPorts(newServerPorts2);
                            }
                            container.setPortMap(portMap);
                        }
                        //结束处理 portMap
                        container.setName(name);
                        container.setImageVersion(imageVersion);
                        container.setCpu(cpu);
                        container.setMemory(memory);
                        container.setVolume(volume);
                        container.setIp(ip);
                        //container.setPortMap(portMap);//前面该删的删了,该加的加了,所以这里不需要再处理了
                        container.setUse(use);
                        container.setEndTime(WebUtils.parseStringToDate(endTime));
                        containerService.updateContainer(container);
                        response.getWriter().write("存入成功");
                    }
                }
            }
            serviceService.updateService(service);
            serverService.updateServer(server);
        }//根据访问方式的不同,予以不同的处理方式,如果是get,那就给与配置服务的页面;如果是post,那就从参数中查询要配置内容
    }
    protected void list(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException{
        String serviceId=request.getParameter("serviceId");
        System.out.println(Thread.currentThread().getStackTrace()[1].getFileName()+":"
                +Thread.currentThread().getStackTrace()[1].getLineNumber()+":"+"当前 serviceId 是: "+serviceId);

        request.setAttribute("serverService",serverService);
        if (serviceId==null){//要展示全部
            List<Server> servers=serviceService.queryServersByServiceName("docker");
            request.setAttribute("servers",servers);

            List<Container> containers=containerService.queryContainers();
            request.setAttribute("containers",containers);
        }else {//不展示全部
            Service service=serviceService.queryServiceById(serviceId);//判断serviceId是否有效
            if(service==null){//判断是否有效 serviceId,有效就展示特定 docker 服务的 container;无效就返回 not found
                response.getWriter().write("serviceId : "+serviceId+" not found");
                return;
            }else{//这是serviceId有效的情况
                request.setAttribute("service",service);
                Server server=serverService.queryServerById(service.getServerId());
                request.setAttribute("server",server);

                List<Server> servers=serverService.queryServers();
                request.setAttribute("servers",servers);

                List<Container> containers=containerService.queryContainersByServerId(server.getId());
                request.setAttribute("containers",containers);
            }//判断是否有效 serviceId,有效就展示特定 docker 服务的 container;无效就返回 not found
        }//没有serviceId就展示全部container

        request.getRequestDispatcher("/pages/client/container.jsp").forward(request,response);


//
//        if(serverId==null){//参数中没有serverId,所以要显示全部的service
//            List<Service> services= serviceService.queryServices();
//            request.setAttribute("services",services);
//            request.setAttribute("serverService",serverService);
//            request.getRequestDispatcher("/pages/client/container.jsp").forward(request,response);
//        }else{//参数中有 serverId,显示相关的service即可
//            Server server=serverService.queryServerById(serverId);
//            if(server==null){
//                response.getWriter().write("找不到id为: "+serverId+" 的服务器");
//                return;
//            }
//            request.setAttribute("server",server);
//            List<Service> services= serviceService.queryServicesByServerId(serverId);
//            request.setAttribute("services",services);
//            request.setAttribute("serverService",serverService);
//            request.setAttribute("serverName",server.getName());
//            request.getRequestDispatcher("/pages/client/container.jsp").forward(request,response);
//        }//参数中有serverId,显示特定服务器的服务;参数中没有 serverId ,显示全部server的服务

    }
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        System.out.println(Thread.currentThread().getStackTrace()[1].getFileName()+":"
                +Thread.currentThread().getStackTrace()[1].getLineNumber()+":"
                +"已经进入doget方法,"+request.getParameter("action")+" 是action名");
        doPost(request,response);//把dopost方法优化到baseServlet抽象类中去了,使得可以按照request action执行特定的方法
        //由于action判断行为在dopost中,所以在doget中执行一下dopost就可以执行判断了,从而执行特定的方法了.
    }
}
